import axios from 'axios'
import { Message, Loading } from 'element-ui'

const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API,
    withCredentials: true,
    timeout: 15000,
})

// 下载文档流
const handleFileResponse = (res) => {
    return new Promise((resolve) => {
        const r = new FileReader()
        r.onload = function () {
            try {
                const result = JSON.parse(this.result)
                resolve(result)
            } catch (error) {
                resolve({
                    result: 'file',
                    data: res,
                })
            }
        }
        r.readAsText(res.data)
    })
}
/**
 * @description 请求头封装 是否需要添加token
 * @param { config | token }
 * @return { Promise }
 */
service.interceptors.request.use(
    (config) => {
        if (config && config.loading && config.loading !== false) {
            const { loading } = config
            const is_num = typeof config.loading === 'number'
            if (is_num) config.loading_num = true
            config.loading = Loading.service({
                lock: true,
                background: `rgba(255, 255, 255, ${is_num ? loading : '0.8'})`,
            })
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

/**
 * @description Responsen返回处理
 * @param { response }
 * @return { Object }
 */
service.interceptors.response.use(
    async (response) => {
        await closeLoading(response)
        let res = response.data

        if (response.config.responseType === 'blob') {
            res = await handleFileResponse(response)
            if (res.result === 1 || res.result === 'file') {
                return res.data
            }
        }
        if (res.result !== 1) {
            Message.closeAll()
            Message({
                message: res.error_msg || res.errorMsg || 'Error',
                type: 'error',
                duration: 2 * 1000,
            })
            return Promise.reject(res)
        } else {
            return response.config?.needResponse ? res : res.data
        }
    },
    async (error) => {
        await closeLoading(error)
        if (error.response === undefined) {
            Message({
                message: '连接超时，请稍候再试！',
                type: 'error',
                duration: 2 * 1000,
            })
        }
        return Promise.reject(error)
    }
)

/**
 * @description 关闭全局加载,延迟200毫秒关闭，以免晃眼睛
 * @param target
 */
const closeLoading = (target) => {
    const { loading, loading_num } = target.config
    if (!loading) return true
    return new Promise((resolve) => {
        setTimeout(
            () => {
                target.config.loading.close()
                resolve()
            },
            loading_num ? 0 : 200
        )
    })
}

export default service
